package com.neveu.android.ds.socketmessenger;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketMessengerActivity extends Activity implements MessageListener, View.OnClickListener {
    /** Called when the activity is first created. */
	
	private NetServent servent;
	private Resources res;
	private TextView tv;
	private EditText portNo;
	private int serverPort = 4321, clientPort = 1234;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        res = this.getResources();
        tv = ((TextView)findViewById(R.id.textview));
        tv.setMovementMethod(new ScrollingMovementMethod());
        portNo = ((EditText)findViewById(R.id.portNo_tb));
        
        //getText(R.string.loopback_ip)
	    Button sendButton = (Button)findViewById(R.id.send_but);
	    Button connectButton = (Button)findViewById(R.id.connect_but);
	    
	    servent = new NetServent(res.getString(R.string.loopback_ip), serverPort, clientPort);
        servent.setMessageListener(this);

	    sendButton.setOnClickListener(this);
	    connectButton.setOnClickListener(this);

	    //			@Override
//			public void onClick(View v) {
//				if(servent.connect())
//				{	
//					CheckBox connectCB = (CheckBox)findViewById(R.id.connect_cb);
//					connectCB.setChecked(true);
//				}
//			}
//		});
    }
  
    public void onClick(View v)
    {
    	switch(v.getId())
    	{
    	case R.id.connect_but:
    		if(!portNo.getText().toString().equals(""))
    			servent.connect(Integer.parseInt(portNo.getText().toString()));
    		break;
    	case R.id.send_but:
			EditText et = (EditText)findViewById(R.id.editText1);
			servent.sendMessage(et.getText().toString());
			et.setText("");
    		break;
    	}
    }

//    @Override
//    public void onStop()
//    {
//    	servent.disconnect();
//    	this.finish();
//    }
    
    public void receiveMessage(final String msg)
    {
    	tv.post(new Runnable() {
            public void run() {
            	tv.append(msg);

            	if(tv.getLineCount() > 5 /* need to way to get max lines */)
            		tv.scrollBy(0, tv.getLineHeight());
            }
    	});
    }

}